/*
 * @Author: TC (tengchao@taqu.cn)
 * @Date: 2025-10-10 14:19:57
 * @Last Modified by: TC (tengchao@taqu.cn)
 * @Last Modified time: 2025-10-11 10:44:01
 */

import { _decorator, Component, easing, HALF_PI, instantiate, Node, Sprite, tween, v3 } from "cc";
import { EMoleEventConst } from "../../../Const/MoleEventConst";
import { BaseComponent } from "db://assets/FrameWork/Module/Component/BaseComponent";
import { gameMole } from "../../../GameMole";
import { app } from "db://assets/FrameWork/App";
const { ccclass, property } = _decorator;

/**
 * 生命界面
 */
@ccclass("MoleHpUI")
export class MoleHpUI extends BaseComponent {
    @property({ type: Node, displayName: "生命列表" })
    private layoutHp: Node = null;
    @property({ type: Node, displayName: "复制节点" })
    private nodeHp: Node = null;

    private _hpMax: number = 10;
    private _hp: number = 10;

    protected init(): void {
        super.init();
    }

    protected addUIEvent(): void {
        super.addUIEvent();
    }

    protected registerEvent(): void {
        super.registerEvent();
        this.register(EMoleEventConst.ReduceHp, this._onReduceHp);
        this.register(EMoleEventConst.AddHp, this._addHp);
    }

    public initUI(): void {
        this._hp = gameMole.dataMgr.hp;
        this._initHpUI();
    }

    /**
     * 初始化生命
     */
    private _initHpUI() {
        this.layoutHp.removeAllChildren();
        for (let i = 0; i < this._hpMax; i++) {
            const nodeHp = instantiate(this.nodeHp);
            nodeHp.parent = this.layoutHp;
        }
        this._refreshHpUI();
    }

    /**
     * 初始化生命
     */
    private _refreshHpUI() {
        const full = Math.floor(this._hp);
        const decimal = this._hp - full;
        // app.log.info("MoleHpUI _refreshHpUI ", full, decimal);
        for (let i = 0, len = this.layoutHp.children.length; i < len; i++) {
            const nodeHp = this.layoutHp.children[i];
            const spt = nodeHp.getChildByName("heart").getComponent(Sprite);
            if (i < full) {
                spt.fillRange = 1;
            } else {
                if (i == full) {
                    spt.fillRange = decimal;
                } else {
                    spt.fillRange = 0;
                }
            }
        }
    }
    /**
     * 减少生命
     */
    private _onReduceHp(damage: number) {
        this._hp -= damage;
        if (this._hp <= 0) {
            this._hp = 0;
            gameMole.battleMgr.endBattle();
        }
        this._refreshHpUI();
    }

    /**
     * 增加生命
     */
    private _addHp(hp: number) {
        this._hp += hp;
        if (this._hp > this._hpMax) {
            this._hp = this._hpMax;
        }
        this._refreshHpUI();
    }
}
